import django_filters
from rest_framework import serializers
from .models import Product


class ProductFilter(django_filters.rest_framework.FilterSet):
    """
    过滤
    """
    account = django_filters.CharFilter(method="account_filter", field_name="account", label="用户名")
    id = django_filters.NumberFilter(field_name="id", label="产品ID")

    def account_filter(self, queryset, name, value):
        from apps.sales_man.models import SalesMan
        salesman = SalesMan.objects.filter(account=value)
        if salesman.exists():
            salesman = salesman.first()
        else:
            raise serializers.ValidationError("参数错误")
        return queryset.filter(channelproduct__status=True, channelproduct__channel=salesman.channel)

    class Meta:
        model = Product
        fields = ["type", "parent_product", "account"]


class ProductCityFilter(django_filters.rest_framework.FilterSet):
    product = django_filters.NumberFilter(method='product_filter', field_name="product")
    province = django_filters.NumberFilter(method='province_filter', field_name="province")

    def product_filter(self, queryset, name, value):
        return queryset.filter(product=value)

    def province_filter(self, queryset, name, value):
        return queryset.filter(province=value)
